package com.zk.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.zk.yygh.enums.PaymentTypeEnum;
import com.zk.yygh.enums.RefundStatusEnum;
import com.zk.yygh.model.order.OrderInfo;
import com.zk.yygh.model.order.PaymentInfo;
import com.zk.yygh.model.order.RefundInfo;
import com.zk.yygh.order.service.OrderService;
import com.zk.yygh.order.service.PaymentService;
import com.zk.yygh.order.service.RefundService;
import com.zk.yygh.order.service.WeiXinService;
import com.zk.yygh.order.utils.ConstantPropertiesUtils;
import com.zk.yygh.order.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: 张凯
 * @date: 2022/6/22 - 17:39
 */
@Service
public class WeiXinServiceImpl implements WeiXinService {

    @Autowired
    private RedisTemplate redisTemplate;

    //订单service
    @Autowired
    private OrderService orderService;

    //支付service
    @Autowired
    private PaymentService paymentService;

    //退款service
    @Autowired
    private RefundService refundService;


    //下单根据orderId生成微信支付二维码链接
    @Override
    public Map<String, Object> createNative(Long orderId) {
        //1.查询redis中看看需要的参数是否存在，存在就直接返回参数
        Map map= (Map) redisTemplate.opsForValue().get(orderId.toString());
        if (map!=null){
            return map;
        }
        //2.向payment_Info表中添加初始的交易记录
        OrderInfo order = orderService.getOrder(orderId);   //获取订单信息
        paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus()); //执行添加：订单信息，支付方式

        //3.封装请求调用微信接口获取生成二维码url的参数
        Map<String,String> paramMap = new HashMap<String,String>();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);   //关联的公众号Id
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER); //商户号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串
        String body = order.getReserveDate() + "就诊"+ order.getDepname();
        paramMap.put("body", body);
        paramMap.put("out_trade_no", order.getOutTradeNo());    //订单交易号
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee", "1"); //交易金额：0.01￥
        paramMap.put("spbill_create_ip", "127.0.0.1");
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//申请绑定的url
        paramMap.put("trade_type", "NATIVE");//二维码方式

        //4.创建HttpClient请求客户端并设置相关参数及发送请求
        HttpClient httpClient=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder"); //访问第三方接口
        try {
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));  //带着请求参数和唯一key进行访问
            httpClient.setHttps(true);  //设置为https
            httpClient.post();  //执行请求

            //5.返回第三方xml数据，并将xml转为map
            String xml = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //6.封装返回结果集
            Map<String,Object> resMap = new HashMap<String,Object>();
            resMap.put("orderId", orderId); //订单Id
            resMap.put("totalFee", order.getAmount());  //服务费
            resMap.put("resultCode", resultMap.get("result_code")); //结果码
            resMap.put("codeUrl", resultMap.get("code_url"));   //生成的微信二维码url
            //7.对结果集的返回状态码进行判断来添加到redis
            if (resultMap.get("result_code")!=null){
                //向redis中添加返回的结果集，两小时的有效时间
                redisTemplate.opsForValue().set(orderId.toString(),resMap,120, TimeUnit.MINUTES);
            }

            //8.最终返回二维码相关参数
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean refund(Long orderId) {
        //获取支付信息(id,type)
        PaymentInfo paymentInfo=paymentService.getPayment(orderId,PaymentTypeEnum.WEIXIN.getStatus());
        //添加退款记录
        RefundInfo refundInfo=refundService.saveRefundInfo(paymentInfo);
        //判断是否已退款
        if (refundInfo.getRefundStatus().intValue()== RefundStatusEnum.REFUND.getStatus()){
            //已经退款
            return true;
        }
        //未退款->封装相关参数->转为xml
        Map<String,String> paramMap = new HashMap<>(8);
        paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo()); //商户退款单号
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");
        try {
            //封装请求客户端并设置参数及证书请求微信退款接口
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            //返回第三方信息
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //退款成功：更新退款信息，支付信息
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
